package com.redhat.auth.exception;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.apache.struts2.json.JSONException;
import org.apache.struts2.json.JSONUtil;

public class AjaxWebUtil {
	/**
     * 输出json数据到web页面
     * @param response
     * @param jsons
     * @throws IOException 
     */
    public static  void writeJSON(HttpServletResponse response, String ... jsons){
        try {
            String json = concatJSON(jsons);
            writeObject(response, json, "text/x-json;charset=UTF-8"); 
        } catch (Exception e) {
        }
        
    }
    
    public static  void writeJSON(HttpServletResponse response, String key ,String value) {
        
        try {
            String template = "{\"{key}\":\"{value}\"}";
            writeObject(response, template.replace("{key}", key).replace("{value}", value), "text/x-json;charset=UTF-8");
        } catch (Exception e) {
        }
    }
    
    
    /**
     * 直接输出HTML.
     * 
     * @param response
     * @param text
     * @throws IOException 
     */
    public static  void writeHTML(HttpServletResponse response, String text) {
        try {
            writeObject(response, text == null ? "" : text, "text/html;charset=UTF-8");
        } catch (Exception e) {}
    }
    
    /**
     * 输出.
     * 
     * @param contentType
     *            内容的类型.html,text,xml的值见后，json为"text/x-json;charset=UTF-8"
     * @throws IOException 
     */
    private static  void writeObject(HttpServletResponse response, String text,
            String contentType) throws IOException {
        response.setContentType(contentType);
        response.getWriter().write(text);
    }
    
   /**
    * 对象转换成json格式字符串<br>
    * 可以选择包含或者忽略的属性列表，支持正则表达式模糊匹配
    * @param obj
    * @param exclude
    * @param properties
    * @return
 * @throws JSONException 
    */
    @SuppressWarnings("unchecked")
    public static String bean2JSON(Object obj , boolean exclude, String properties) throws JSONException{

        StringBuffer json = new StringBuffer();
        String name = null;
        Collection<Pattern> includeProperties = null;
        Collection<Pattern> excludeProperties = null;
        if(StringUtils.isNotEmpty(properties)){
            if(exclude){
                excludeProperties = new ArrayList<Pattern>();
                excludeProperties.add(Pattern.compile(properties));
            }else{
                includeProperties = new ArrayList<Pattern>();
                includeProperties.add(Pattern.compile(properties));
            }
            
        }
        if(obj.getClass()== ArrayList.class){
            List<Object> list = (List<Object>) obj;
            for (Object bean : list) {
                if(name==null)
                    name = bean.getClass().getSimpleName();
                json.append(JSONUtil.serialize(bean, excludeProperties, includeProperties, true, true))
                .append(",");
            }
            json.deleteCharAt(json.length()-1);
        }else{
            name = obj.getClass().getSimpleName();
            json.append(JSONUtil.serialize(obj, excludeProperties, includeProperties, true, true));
        }
        String template = "{\"{name}\":[{json}]}";
        return template.replace("{name}", name).replace("{json}", json.toString());
    
    }
    
    /**
     * 多个json对象组装
     * @param jsons
     * @return
     */
    private static String concatJSON(String ... jsons){
        
        if(jsons == null || jsons.length==0)return "";
        
        if(jsons.length==1)return jsons[0];
        
        StringBuffer buff = new StringBuffer("{");
        
        for (String json : jsons) {
            if(json.startsWith("{")){
                json = json.substring(1, json.length()-1);
            }
            buff.append(json).append(",");
        }
        
        buff.deleteCharAt(buff.length()-1);
        buff.append("}");
        return buff.toString();
    }
}
